package com.iflytek.ci.common.service.impl;

import com.iflytek.ci.common.service.Autobuild;
//import com.iflytek.ci.cpms.service.util.MilestoneReprterService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Created with IntelliJ IDEA. User: liyasoft Date: 13-1-25 Time: 下午5:13 To
 * change this template use File | Settings | File Templates.
 */
public class AutobuildImpl{
	private static final Logger logger = LoggerFactory
			.getLogger(Autobuild.class);

	public int build(String src_url, long milestone_id,String tag_name, String releaseVersion,
			String projectName) {
		String bat_path = "/iflytek/cdms/bat/autobuild.bat ";
		String logPath = "/iflytek/cdms/log/".concat(projectName).concat("-")
				.concat(String.valueOf(milestone_id)).concat("_build.log");
		String options = src_url.concat(" ").concat(tag_name).concat(" ")
				.concat(releaseVersion).concat(" >> ").concat(logPath);
		System.out.println("[INFO]" + bat_path + options);
		try {
			Process process = Runtime.getRuntime().exec(
					"cmd /c " + bat_path + options);
			InputStream in = process.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String tmp = "";
			while ((tmp = br.readLine()) != null) {
				System.out.println(tmp);
			}
			try {
				process.waitFor();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} catch (IOException ioe) {
			logger.info("创建进程并调用外部命令失败");
			return 1;
		}
		try {
			return isBuildSuccess(logPath);
		} catch (Exception e) {
			logger.info("[ERROR] 日志文件读取失败");
			return 1;
		}

	}

	public int isBuildSuccess(String fileName) {
		File file = new File(fileName);
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				System.out.println("line " + line + ": " + tempString);
				if (tempString.indexOf("BUILD FAILURE") > 0) {
					return 1;
				}
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
			return 1;
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					return 1;
				}
			}
		}
		return 0;
	}
}
